package com.shizhanzhe.zxbapp.vip;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.Nullable;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.gyf.barlibrary.ImmersionBar;
import com.shizhanzhe.zxbapp.R;
import com.shizhanzhe.zxbapp.bean.CircleDetailsBean;
import com.shizhanzhe.zxbapp.bean.UserBean;
import com.shizhanzhe.zxbapp.bean.ZanFq;
import com.shizhanzhe.zxbapp.customtask.PictureUploadActivity;
import com.shizhanzhe.zxbapp.customtask.PictureUploadDetailsActivity;
import com.shizhanzhe.zxbapp.pay.PayVIP;
import com.shizhanzhe.zxbapp.url.Path;
import com.shizhanzhe.zxbapp.utils.AdPreference;
import com.shizhanzhe.zxbapp.utils.BnfStartupAdPageDto;
import com.shizhanzhe.zxbapp.utils.DownListener;
import com.shizhanzhe.zxbapp.utils.DownloadUtil;
import com.shizhanzhe.zxbapp.utils.OkHttpDownloadJsonUtil;
import com.shizhanzhe.zxbapp.utils.SharedPreferencesUtils;
import com.shizhanzhe.zxbapp.widget.CountdownTextView;
import com.shizhanzhe.zxbapp.widget.ExitDialog;
import com.shizhanzhe.zxbapp.widget.VipDIalog;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.wechat.moments.WechatMoments;

/**
 * @author YJ
 * @date 2019/3/19
 */
public class HairCircleDetailsActivity extends Activity {
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.title)
    TextView mTitle;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.text)
    TextView text;

    @BindView(R.id.tv_commit)
    TextView tvCommit;
    @BindView(R.id.tv_status)
    TextView tvStatus;
    @BindView(R.id.tv_time)
    CountdownTextView tvTime;
    @BindView(R.id.ll_jinxing)
    LinearLayout llJinxing;
    private int taskid;
    private int status = 0;
    private int keeptime = 0;
    private int again = 0; //1确定放弃上个任务
    private String codeimg = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_hair_circle_details);
        ButterKnife.bind(this);
        ImmersionBar.with(this)
                .fitsSystemWindows(true)  //使用该属性,必须指定状态栏颜色
                .statusBarColor(R.color.colorAccent)
                .init();
        taskid = getIntent().getIntExtra("taskid",0);
        initData();
    }

    private void initData() {
        topTitle.setText("详情");
        zanFq();
        quanDetail();
    }

    @OnClick({R.id.backarea, R.id.tv_commit, R.id.tv_status, R.id.tv_circle_save, R.id.tv_shangchuan, R.id.tv_circle_copy})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.backarea:
                finish();
                break;
            case R.id.tv_commit:
                if (UserBean.level > 0) {
                    receive();
                } else {
                    final VipDIalog vipDIalog = new VipDIalog(HairCircleDetailsActivity.this);
                    vipDIalog.setVIPListener(new VipDIalog.VIPListener() {
                        @Override
                        public void chooseTrue() {
                            startActivity(new Intent(HairCircleDetailsActivity.this, PayVIP.class));
                            vipDIalog.dismiss();
                        }

                        @Override
                        public void chooseFalse() {
                            vipDIalog.dismiss();
                        }
                    });
                    vipDIalog.show();
                }
                break;
            case R.id.tv_status:
                //查看上传信息
                if (status != 4) {
                    startActivity(new Intent(HairCircleDetailsActivity.this, PictureUploadDetailsActivity.class)
                            .putExtra("isshow", 2).putExtra("checkid", taskid));
                }
                break;
            case R.id.tv_circle_save:

                SavePyq();
//                sharePyq();
                break;
            case R.id.tv_shangchuan:
                startActivityForResult(new Intent(this, PictureUploadActivity.class).putExtra("taskid", taskid)
                        .putExtra("examplepic", "0"), 110);
                break;
            case R.id.tv_circle_copy:
//                cancelTask(UserBean.uid,taskid);
                ClipboardManager cm = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
                cm.setText(text.getText().toString());
                Toast.makeText(HairCircleDetailsActivity.this, "复制成功", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }
    private void zanFq(){
        OkHttpDownloadJsonUtil.downloadJson(HairCircleDetailsActivity.this, Path.zanFq(), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        ZanFq zanFq = new Gson().fromJson(json, ZanFq.class);
                        StringBuffer text = new StringBuffer();
                        for (int i = 0 ;i<zanFq.getData().size();i ++){
                            text.append("累积<font color=\"#149CF3\">"+zanFq.getData().get(i).getZannum()+"</font>个赞=<font color=\"#FF0000\">"+zanFq.getData().get(i).getMoney()+"</font>元<br>");
                        }
                        mTitle.setText(Html.fromHtml("分享以下图文到朋友圈集赞获得奖励：<br><br>"+text.toString()));
                    } catch (Exception e){
                        Log.d("____",e.toString());
                        Toast.makeText(HairCircleDetailsActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(HairCircleDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    //获取详情
    private void quanDetail() {
        OkHttpDownloadJsonUtil.downloadJson(HairCircleDetailsActivity.this, Path.quanDetail(UserBean.uid,taskid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @SuppressLint("SetTextI18n")
            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        CircleDetailsBean detailsBean = new Gson().fromJson(json, CircleDetailsBean.class);
//                        mTitle.setText(detailsBean.getData().getTitle());
                        Log.d("____",detailsBean.getData().getCodeimg());
                        Glide.with(HairCircleDetailsActivity.this).load(Path.img(detailsBean.getData().getCodeimg()))
                                .apply(new RequestOptions().placeholder(R.mipmap.logo2)).into(iv);
                        text.setText(detailsBean.getData().getScon());
                        keeptime = detailsBean.getData().getKeeptime();
                        status = detailsBean.getStatus();
                        codeimg = Path.img(detailsBean.getData().getCodeimg());
                        //审核状态 -2未领取 1已领取 2待审核 3审核成功 -1审核失败 4任务超时
                        switch (status) {
                            case -2:
                                tvCommit.setVisibility(View.VISIBLE);
                                llJinxing.setVisibility(View.GONE);
                                tvStatus.setVisibility(View.GONE);
                                break;
                            case 1:
                                long endtime = Long.parseLong((String) SharedPreferencesUtils.getParam(HairCircleDetailsActivity.this, "timer1", ""));
                                long time = endtime - System.currentTimeMillis() / 1000;
                                tvTime.init("过期倒计时:%s", time);
                                tvTime.start(0);
                                llJinxing.setVisibility(View.VISIBLE);
                                tvCommit.setVisibility(View.GONE);
                                tvStatus.setVisibility(View.GONE);
                                break;
                            default:
                                tvStatus.setVisibility(View.VISIBLE);
                                llJinxing.setVisibility(View.GONE);
                                tvCommit.setVisibility(View.GONE);
                                switch (status) {
                                    case 2:
                                        tvStatus.setText("审核中");
                                        break;
                                    case 3:
                                        tvStatus.setText("审核成功");
                                        break;
                                    case -1:
                                        tvStatus.setText("审核失败");
                                        break;
                                    case 4:
                                        tvStatus.setText("任务超时");
                                        break;
                                    default:
                                        break;
                                }
                                break;
                        }
                    } catch (Exception e){
                        Log.d("____",e.toString());
                        Toast.makeText(HairCircleDetailsActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(HairCircleDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
    //领取任务
    private void receive() {
        OkHttpDownloadJsonUtil.downloadJson(HairCircleDetailsActivity.this, Path.lingFq(UserBean.uid, taskid), new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {

            @Override
            public void onsendJson(String json) {
                if (!"1".equals(json) && !"2".equals(json)) {
                    try {
                        final JSONObject jsonObject = new JSONObject(json);
                        if (jsonObject.has("status")) {
                            if (jsonObject.getInt("status") == 1) {
                                Toast.makeText(HairCircleDetailsActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                                quanDetail();
                                SharedPreferencesUtils.setParam(HairCircleDetailsActivity.this, "timer1",  (System.currentTimeMillis() / 1000 + keeptime)+"");
                            } else if (jsonObject.getInt("status") == 3){
                                final ExitDialog mExitDialog = new ExitDialog(HairCircleDetailsActivity.this);
                                mExitDialog.setExitListener(new ExitDialog.ExitListener() {
                                    @Override
                                    public void chooseTrue() {
                                        //确定结束上个任务，开始当前任务
                                        mExitDialog.dismiss();
                                        if (jsonObject.has("taskid")){
                                            try {
                                                again = 1;
                                                cancelTask(UserBean.uid, jsonObject.getInt("taskid"));
                                            } catch (JSONException e) {
                                                e.printStackTrace();
                                            }
                                        }
                                    }

                                    @Override
                                    public void chooseFalse() {
                                        //取消
                                        mExitDialog.dismiss();
                                    }
                                });
                                mExitDialog.show();
                                mExitDialog.setTask(jsonObject.getString("info"));
                            } else {
                                Toast.makeText(HairCircleDetailsActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }
    //取消任务
    private void cancelTask(int uid, int taskid) {
        OkHttpDownloadJsonUtil.downloadJson(this, Path.quxiaoFq(uid,taskid),
                new OkHttpDownloadJsonUtil.onOkHttpDownloadListener() {
                    @Override
                    public void onsendJson(String json) {
                        if (!"1".equals(json) && !"2".equals(json)) {
                            try {
                                JSONObject jsonObject = new JSONObject(json);
                                if (jsonObject.has("status")) {
                                    Toast.makeText(HairCircleDetailsActivity.this, jsonObject.getString("info"), Toast.LENGTH_SHORT).show();
                                    if (jsonObject.getInt("status") == 1) {
                                        if (again == 1) {
                                            receive();
                                            again = 0;
                                        } else {
                                            quanDetail();
                                        }
                                    }
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        } else {
                            Toast.makeText(HairCircleDetailsActivity.this, "网络异常", Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }
    private void SavePyq(){
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("正在保存...");
        dialog.show();
        //
        AdPreference.getInstance().saveStartupAdPage(new BnfStartupAdPageDto(codeimg, "", "1536809117"));
        new DownloadUtil().downloadImg(Environment.getExternalStorageDirectory() + "/MFAdYD/", codeimg, new DownListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(int currentLength) {

            }

            @Override
            public void onFinish(final String localPath) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Toast.makeText(HairCircleDetailsActivity.this, "保存成功", Toast.LENGTH_SHORT).show();
                    }
                });

            }

            @Override
            public void onFailure() {
                dialog.dismiss();
                AdPreference.getInstance().clear();
            }
        });
    }
    //分享到朋友圈
    private void sharePyq(){
        final ProgressDialog dialog = new ProgressDialog(this);
        dialog.setMessage("正在生成...");
        dialog.show();
        //
        AdPreference.getInstance().saveStartupAdPage(new BnfStartupAdPageDto(codeimg, "", "1536809117"));
        new DownloadUtil().downloadImg(Environment.getExternalStorageDirectory() + "/MFAdYD/", codeimg, new DownListener() {
            @Override
            public void onStart() {

            }

            @Override
            public void onProgress(int currentLength) {

            }

            @Override
            public void onFinish(final String localPath) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        dialog.dismiss();
                        Platform.ShareParams weM = new Platform.ShareParams();
                        weM.setImagePath(localPath);
                        weM.setShareType(Platform.SHARE_IMAGE);
                        Platform WechatM = ShareSDK.getPlatform(WechatMoments.NAME);
                        WechatM.share(weM);
                    }
                });

            }

            @Override
            public void onFailure() {
                dialog.dismiss();
                AdPreference.getInstance().clear();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 110 && resultCode == 110){
            initData();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }
}
